package com.bp.hearthealth.pulse.lnapps.bp_network

import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.google.gson.GsonBuilder
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit
import javax.net.ssl.*

object BpRetrofitManager {

    private val mOkClient = OkHttpClient.Builder()
        .callTimeout(20, TimeUnit.SECONDS)
        .connectTimeout(20, TimeUnit.SECONDS)
        .readTimeout(20, TimeUnit.SECONDS)
        .writeTimeout(20, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .followRedirects(false)
//        .cookieJar(LocalCookieJar())
//        .addInterceptor(TokenInterceptor())
//        .addInterceptor(HttpHeadInterceptor())
        .addInterceptor(initCommonInterceptor())
        .addInterceptor(LoggingInterceptor())

    private var mRetrofit: Retrofit? = null


    fun initRetrofit(): BpRetrofitManager {
//        ignoreSSLCheck()
        mRetrofit = Retrofit.Builder()
            .baseUrl("https://baidu.com")
            .client(mOkClient.build())
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(
                GsonConverterFactory.create(
                    GsonBuilder().registerTypeAdapterFactory(BpGsonTypeAdapterFactory()).create()
                )
            )

            .build()
        return this
    }

    fun <T> getService(serviceClass: Class<T>): T {
        if (mRetrofit == null) {
            throw UninitializedPropertyAccessException("Retrofit必须初始化")
        } else {
            return mRetrofit!!.create(serviceClass)
        }
    }

    private class LoggingInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            val response = chain.proceed(chain.request())
            val responseBody = response.body ?: return response
            val mediaType = responseBody.contentType()
            val content = response.body!!.string()
            LogUtil.i("请求地址:  $request")
            LogUtil.i(content)
            return response.newBuilder().body(ResponseBody.create(mediaType, content)).build()
        }
    }


    private fun initCommonInterceptor(): Interceptor {
        return Interceptor { chain ->
            val request = chain.request()
                .newBuilder()
                .addHeader("Content-Type", "BaseApplicationlication/json")
                .addHeader("charset", "UTF-8")
                .build()
            chain.proceed(request)
        }
    }

}